package com.ladlee.handle;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ladlee.enums.ResultEnum;
import com.ladlee.utils.ResultUtils;
import com.ladlee.validata.exception.ValidateCodeException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Auther: dingchang
 * @Date: 2018/12/22 15:03
 * @Description: 自定义登录失败处理
 */
@Component(value = "loginFailHandler")
public class LoginFailHandler extends SimpleUrlAuthenticationFailureHandler {

    @Autowired
    ObjectMapper objectMapper;

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        String message = "";
        response.setContentType("application/json;charset=UTF-8");
        if(exception instanceof BadCredentialsException){
            message = "用户名或密码错误";
            response.getWriter().write(objectMapper.writeValueAsString(ResultUtils.error(ResultEnum.FAIL.getCode(), message)));
        }else if(exception instanceof ValidateCodeException){
            response.getWriter().write(objectMapper.writeValueAsString(ResultUtils.error(ResultEnum.CODE_ERROT.getCode(), exception.getMessage())));
        }else{
            response.getWriter().write(objectMapper.writeValueAsString(ResultUtils.error(ResultEnum.FAIL.getCode(), exception.getMessage())));
        }
    }
}
